<template>
  <div class="chat-container">
    <div class="chat-history" id="chat-history">
      <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
        <div class="message-content">
          <strong>{{ msg.role === 'user' ? 'Q' : 'A' }}:</strong>
          <div v-html="parseMarkdown(msg.content)" class="markdown-content"></div>
        </div>
      </div>
      <div v-if="isStreaming" class="message assistant">
        <div class="message-content">
          <strong>Assistant:</strong>
          <div v-html="parseMarkdown(partialResponse)" class="markdown-content"></div>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <input v-model="userInput" @keyup.enter="sendMessage" placeholder="聊点什么吧" />
      <el-button type="primary" @click="sendMessage" >
        <el-icon><Position /></el-icon>
        Send 
      </el-button>
    </div>
   
  </div>
</template>

<script setup>
import { ref,onMounted } from 'vue';
import { sendMessage as sendToAPI } from '../services/api';
import { parseMarkdown } from '../utils/markdown'; // 导入 Markdown 解析工具
// 定义响应式数据
const userInput = ref('');
const messages = ref([]);
const partialResponse = ref(''); // 用于存储流式传输的部分响应
const isStreaming = ref(false); // 是否正在流式传输

// 获取屏幕高度
onMounted(() => {
  const screenHeight = window.innerHeight;
  // 设置chat-history的高度
  const chatHistory = document.getElementById('chat-history');
  chatHistory.style.height = `${screenHeight - 120}px`; // 减去输入框和按钮的高度
})
// 发送消息的函数
const sendMessage = async () => {
  if (userInput.value.trim() === '') return;

  // 添加用户消息到对话历史
  messages.value.push({ role: 'user', content: userInput.value });

  // 清空输入框
  userInput.value = '';

  // 开始流式传输
  isStreaming.value = true;
  partialResponse.value = '';

  try {
    // 调用 API 发送消息并获取流式响应
    const stream = await sendToAPI(messages.value);

    // 创建流式读取器
    const reader = stream.getReader();
    const decoder = new TextDecoder('utf-8');

    // 逐步读取流式数据
    while (true) {
      const { done, value } = await reader.read();
      if (done) break; // 流式传输结束

      // 解码 chunk 数据
      const chunk = decoder.decode(value, { stream: true });
      const lines = chunk.split('\n\n'); // 按分隔符拆分 chunk

      // 处理每个 chunk
      lines.forEach((line) => {
        if (line.trim() === '' || line.trim() === '[DONE]') {
          return; // 跳过空行或结束标记
        }

        try {
          // 解析 JSON 数据
          const data = JSON.parse(line.replace('data:', '').trim());

          // 更新部分响应
          if (data.choices && data.choices[0].delta.content) {
            partialResponse.value += data.choices[0].delta.content;
          }
        } catch (error) {
          console.error('Error parsing chunk:', error);
        }
      });
    }

    // 流式传输结束后，将完整响应添加到对话历史
    messages.value.push({ role: 'assistant', content: partialResponse.value });
  } catch (error) {
    console.error('Error:', error);
  } finally {
    // 结束流式传输
    isStreaming.value = false;
    partialResponse.value = '';
  }
};
</script>

<style>
/* 聊天容器样式 */
.chat-container {
  width: 96%;
  margin: 0 auto;
  padding: 10px;
  border: 1px solid #ccc;
  background-color: #f9f9f9;
}

/* 聊天历史样式 */
.chat-history {
  height: auto;
  font-size: 16px;
  min-height: 580px;
  overflow-y: auto;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #fff;
}

/* 消息通用样式 */
.message {
  margin-bottom: 10px;
}

.message-content {
  padding: 10px;
  border-radius: 5px;
  max-width: 80%;
}

/* 用户消息样式 */
.message.user {
  display: flex;
  justify-content: flex-end;
}

.message.user .message-content {
  background-color: #007bff;
  color: white;
}

/* AI 消息样式 */
.message.assistant {
  display: flex;
  justify-content: flex-start;
}

.message.assistant .message-content {
  background-color: #e9ecef;
  color: black;
}

/* 输入框样式 */
.chat-input {
  width: 96%;
  position: fixed;
  bottom: 0;
  display: flex;
  align-items: center;
}

.chat-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}

.chat-input button {
  width: 80px;
  height: 39px;
  margin-left: 10px;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.chat-input button:hover {
  background-color: #0056b3;
}

/* Markdown 内容样式 */
.markdown-content {
  margin-top: 8px;
}

/* 代码块样式 */
.markdown-content pre {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
}

.markdown-content code {
  font-family: 'Courier New', Courier, monospace;
  color: #d63384;
}

/* 高亮代码块样式 */
.markdown-content .hljs {
  background-color: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
}
</style>